<template>
  <el-card>
  <el-tree
    :props="treeProps"
    :data="treeList"
    node-key="id"
    show-checkbox
    default-expand-all
    :default-checked-keys="a"
  />
  <div class="flex">
  <el-button type="primary" @click="clickHandle">保存</el-button>
  <el-button>清空</el-button>
</div>
</el-card>
</template>

<script lang="ts" setup>
import { ElMessageBox,ElMessage } from 'element-plus';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {getTreeListAPI,getMenuByIdAPI,allocMenuAPI} from './api'


const treeList=ref<ITreeModel[]>([])
const treeProps={
  children:'children',
  label:'title',
}
const router=useRoute()

const a=ref<number[]>([])
if(router.query.id){
  Promise.all([
  getTreeListAPI(),
  getMenuByIdAPI(parseInt(router.query.id as string))
  ]).then(res=>{
    console.log(res[0].data);
    console.log(res[1].data);
    
    treeList.value=res[0].data

    res[1].data.forEach(item=>{
      a.value.push(item.parentId)
    })
  })
}

const torouter=useRouter()
const clickHandle=()=>{
ElMessageBox.confirm('此操作将修改当前用户, 是否继续?','提示',{
  confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
}).then(()=>{
  allocMenuAPI({
  roleId:parseInt(router.query.id as string),
  resourceIds:treeList.value.reduce<number[]>((pre,cur)=>{
    return pre.concat(cur.id)
  },[]),
})
ElMessage.success('修改成功');
torouter.push('/ums/role')
}).catch(()=>{})

}

</script>
<style lang="less" scoped>
.flex {
padding: 20px;
display: flex;
justify-content: center;
}
</style>